package com.tt.cline.service;

import com.alibaba.fastjson.JSONObject;
import com.tt.cline.utils.GetHttpURLConnection;
import com.tt.qiyuesuo.pojo.FileInfo;
import com.tt.qiyuesuo.utils.Response;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;

/**
 * @author tiantao
 * @date 2022/2/22 20:32
 */
public class FileService {
    private static Logger logger = LoggerFactory.getLogger(FileService.class);

    private static final JSONObject JSON = new JSONObject();
    private static final String UPLOAD_REQUEST_PATH = "http://localhost:8080/upload";
    private static final String DOWMLOAD_REQUEST_PATH = "http://localhost:8080/download";
    private static final String GETFILEINFO_REQUEST_PATH = "http://localhost:8080/getFileInfo";
    private static final String BOUNDARY = "----------20140501-----------";


    /**
     * 获取文件元数据
     * @param fileName
     * @return
     */
    public static FileInfo getFileInfo(String fileName){
        InputStream in = null;
        BufferedReader br = null;
        FileInfo fileInfo = null;
        try{

            HttpURLConnection httpURLConnection = GetHttpURLConnection.buildRequestBaseInfo(GETFILEINFO_REQUEST_PATH,"fileName",fileName);
            in = httpURLConnection.getInputStream();// send request to
            // server
            StringBuffer stringBuffer = new StringBuffer();

            br = new BufferedReader(new InputStreamReader(in, "UTF-8"));

            StringBuffer sbf = new StringBuffer();
            // 读取封装的输入流
            String temp = null;
            while ((temp = br.readLine()) != null) {
                sbf.append(temp).append("\r\n");
            }
            if(!StringUtils.isEmpty(sbf)) {
                Response<FileInfo> resp = JSONObject.parseObject(sbf.toString(), Response.class);
                fileInfo = JSONObject.parseObject(JSONObject.toJSONString(resp.getData()), FileInfo.class);
                logger.info("获取文件元数据:{}",JSONObject.toJSONString(fileInfo));
            }else {
                logger.error("文件元数据获取失败，请求返回结果：{}",sbf);
            }

        }catch(Exception e){
            e.printStackTrace();
            logger.error("下载失败，{}",JSONObject.toJSONString(fileInfo));
            return fileInfo;
        }finally{
            try {
                if(in != null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if(br != null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return fileInfo;
    }

    /**
     * 通过httpClient上传文件
     * @param fileName
     * @param path
     * @return 文件名称
     */
    public static String uploadFile(String fileName,String path) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        InputStream content = null;
        BufferedReader in = null;
        String result = "";
        try {
            HttpPost httpPost = new HttpPost(UPLOAD_REQUEST_PATH);
            //HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            httpPost.addHeader("header1", "111");//头部放文件上传的head可自定义
            File file = new File(path+fileName); //上传文件的路径
            //这里定义携带参数
            builder.addBinaryBody("file", file, ContentType.MULTIPART_FORM_DATA, fileName);
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);// 执行提交
            HttpEntity responseEntity = response.getEntity();//接收调用外部接口返回的内容
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                content = responseEntity.getContent();
                // 定义BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
//                logger.info("返回结果为{}",result);
//                if(!StringUtils.isEmpty(result)) {
//                    Response<String> resp = JSONObject.parseObject(result, Response.class);
//                    url = resp.getData();
//                    logger.info("上传文件"+fileName+"返回参数(文件名)==>"+resp.getData());
//                }else {
//                    logger.error("上传文件失败：返回result为null");
//                }
//
            }
        }catch(Exception e) {
            logger.error("上传文件失败：",e);
        }finally {//处理结束后关闭httpclient的链接
            try {
                httpClient.close();
                content .close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    /**
     * 下载文件
     * @param fileName
     * @param localFileName
     * @throws IOException
     */
    public static void downloadFile(String fileName,String localFileName) throws IOException {

        FileOutputStream out = null;
        InputStream in = null;

        try{
            HttpURLConnection httpURLConnection = GetHttpURLConnection.buildRequestBaseInfo(DOWMLOAD_REQUEST_PATH,"fileName",fileName);
            in = httpURLConnection.getInputStream();// send request to
            // server
            File file = new File(localFileName);
            if(!file.exists()){
                file.createNewFile();
            }

            out = new FileOutputStream(file);
            byte[] buffer = new byte[4096];
            int readLength = 0;
            while ((readLength=in.read(buffer)) > 0) {
                byte[] bytes = new byte[readLength];
                System.arraycopy(buffer, 0, bytes, 0, readLength);
                out.write(bytes);
            }

            out.flush();
        }catch(Exception e){
            e.printStackTrace();
            logger.error("下载失败，{}",e);
        }finally{
            try {
                if(in != null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if(out != null){
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String args[]) throws Exception{
        String s = uploadFile("1.jpg", "C:\\Users\\yqn\\Pictures\\Camera Roll\\");
        downloadFile(s,"D:\\project\\"+s);
        getFileInfo(s);


    }
}
